<template>
  <div class="app-container Profile-container">
    <div class="sidebar">
      <div class="head">
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :auto-upload="false"
          :on-change="handleAvatarUpload" accept="image/*">
          <div class="avatar-box">
            <el-avatar :size="50" :src="avatarUrl" class="avatar" v-if="user.avatar" />
            <div class="avatar-hover">更换头像</div>
          </div>
        </el-upload>
        <span class="username">{{ user.realName }}</span>
      </div>
      <div class="custom-menu">
        <div :class="['menu-btn', { active: activeMenu === 'ability' }]" @click="selectMenu('ability')">面试能力</div>
        <div :class="['menu-btn', { active: activeMenu === 'resume' }]" @click="selectMenu('resume')">我的简历</div>
        <!-- 子按钮，仅在“我的简历”激活时显示 -->
        <div v-if="activeMenu === 'resume'" v-for="item in resumeSubTabs" :key="item.name"
          :class="['sub-btn', { active: resumeView === item.name }]" @click="resumeView = item.name">{{ item.label }}
        </div>
        <div :class="['menu-btn', { active: activeMenu === 'record' }]" @click="selectMenu('record')">面试记录</div>
        <div :class="['menu-btn', { active: activeMenu === 'account' }]" @click="selectMenu('account')">账号设置</div>
      </div>
    </div>
    <div class="main-content">
      <!-- 面试能力 -->
      <div v-if="activeMenu === 'ability'">
        <InterviewAbility />
      </div>
      <!-- 我的简历 -->
      <div v-if="activeMenu === 'resume'">
        <!-- <div v-if="resumeView === '制作简历'">
          <ResumeMake />
        </div>
        <div v-if="resumeView === '简历润色'">
          <ResumePolish />
        </div> -->
        <div v-if="resumeView === '简历解析/画像/润色'">
          <ResumeSDK />
        </div>
        <div v-if="resumeView === '简历版本管理'">
          <ResumeList />
        </div>
      </div>
      <!-- 面试记录 -->
      <div v-if="activeMenu === 'record'">
        <InterviewRecord />
      </div>
      <!-- 账号设置：沿用原有tab -->
      <div v-if="activeMenu === 'account'">
        <el-tabs v-model="activeTab" class="profile-tabs">
          <el-tab-pane label="个人资料" name="user">
            <UserInfo ref="user" :user='user' v-if="visible.user" />
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="password">
            <Password ref="password" v-if="visible.password" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import { UserSettingInfo, getSubordinate, UpdateAvatar, UpdateLanguage } from '@/api/permission/userSetting'
import OSS from 'ali-oss'
import UserInfo from './components/UserInfo'
import Password from './components/Password'
import InterviewRecord from './components/interviewrecord'
import InterviewAbility from './components/interviewability'
import ResumeList from './components/resume.vue' // 新增引入
import ResumeSDK from './components/resumeSDK.vue' // 新增引入
import ResumeMake from './components/resumeMake.vue' // 新增引入
import ResumePolish from './components/resumePolish.vue' // 新增引入

export default {
  name: 'profile',
  components: { UserInfo, Password, InterviewRecord, InterviewAbility, ResumeList, ResumeSDK, ResumeMake, ResumePolish }, // 注册组件
  data() {
    return {
      user: {},
      activeMenu: 'ability', // 当前主菜单
      resumeView: '', // 我的简历子按钮
      resumeSubTabs: [
        // { name: '制作简历', label: '制作简历' },
        // { name: '简历润色', label: '简历润色' },
        { name: '简历解析/画像/润色', label: '简历解析/画像/润色' },
        { name: '简历版本管理', label: '简历版本管理' }
      ],
      activeTab: 'user',
      visible: {
        user: true,
        password: false
      },
      uploadHeaders: { Authorization: this.$store.getters.token },
      ossConfig: {
        region: 'oss-cn-wuhan-lr',
        accessKeyId: 'LTAI5tE1sjS9v6rVPid3HXzr',
        accessKeySecret: 'd3dCLmg0CBQgMX5fbSjZc6qMPWJcMj',
        bucket: 'mangopdf',
        endpoint: 'https://mangopdf.oss-cn-wuhan-lr.aliyuncs.com'
      }
    }
  },
  computed: {
    avatarUrl() {
      if (!this.user.avatar) return '';

      // 如果已经是完整URL则直接返回
      if (this.user.avatar.startsWith('http')) {
        return this.user.avatar;
      }

      // 处理后端返回的API路径格式
      if (this.user.avatar.startsWith('/api/file/Image/userAvatar/')) {
        const filename = this.user.avatar.split('/').pop();
        return `${this.ossConfig.endpoint}/avatars/${filename}`;
      }

      // 默认处理其他情况
      return this.user.avatar.startsWith('avatars/')
        ? `${this.ossConfig.endpoint}/${this.user.avatar}`
        : `${this.ossConfig.endpoint}/avatars/${this.user.avatar}`;
    }
  },
  watch: {
    activeTab(val) {
      for (let key of Object.keys(this.visible)) {
        this.visible[key] = false
      }
      this.visible[val] = true
    }
  },
  created() {
    this.getInfo()
  },
  methods: {
    selectMenu(menu) {
      this.activeMenu = menu
      // 切换到“我的简历”时默认选中第一个子项
      if (menu === 'resume') this.resumeView = this.resumeSubTabs[0].name
      // 切换到账号设置时默认tab
      if (menu === 'account') this.activeTab = 'user'
    },
    getInfo() {
      UserSettingInfo().then(res => {
        this.user = res.data
      })
    },
    async handleAvatarUpload(file) {
      try {
        this.loading = true;

        // 验证文件
        const rawFile = file.raw;
        if (!rawFile) {
          throw new Error('未选择文件');
        }

        // 1. 初始化华为云OSS客户端
        const client = new OSS({
          region: this.ossConfig.region,
          accessKeyId: this.ossConfig.accessKeyId,
          accessKeySecret: this.ossConfig.accessKeySecret,
          bucket: this.ossConfig.bucket
        });

        // 2. 生成唯一文件名
        const extension = rawFile.name.split('.').pop();
        const fileName = `avatars/${Date.now()}.${extension}`;

        // 3. 上传到OSS
        const result = await client.put(fileName, rawFile);

        // 4. 获取文件URL
        const avatarUrl = result.url;

        // 5. 更新用户头像
        const afile = avatarUrl.split('/').pop();
        await this.updateAvatar(afile);

        this.$message.success('头像上传成功');
      } catch (error) {
        console.error('头像上传失败:', error);
        this.$message.error('头像上传失败');
      } finally {
        this.loading = false;
      }
    },
    async updateAvatar(fileName) {
      try {
        await UpdateAvatar(fileName);
        this.fetchUserInfo();
      } catch (error) {
        console.error('头像更新失败:', error);
        this.$message.error('头像更新失败');
      }
    },
    fetchUserInfo() {
      UserSettingInfo().then(res => {
        this.user = res.data || this.user
      }).catch(err => {
        console.error('获取用户信息失败', err)
      })
    },
  }
}
</script>

<style lang="scss" scoped>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: rgb(80, 73, 44);
}

.Profile-container {
  display: flex;
  min-height: 100vh;
  background-color: rgb(255, 250, 240);

  .sidebar {
    width: 210px;
    background: linear-gradient(135deg, #f9f7f2 0%, #f6f3ea 100%);
    padding: 18px 10px 18px 10px;
    box-sizing: border-box;
    border-radius: 16px;
    margin: 24px 0 24px 24px;
    box-shadow: 0 2px 12px 0 rgba(200, 180, 120, 0.08);
    border: 1px solid #f0e6d2;

    .head {
      width: 100%;
      padding: 20px 0 10px 0;
      text-align: center;

      .avatar-uploader {
        display: inline-block;

        .avatar-box {
          position: relative;
        }

        .avatar {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          margin-bottom: 8px;
        }

        .avatar-hover {
          position: absolute;
          left: 0;
          top: 0;
          font-size: 12px;
          display: none;
          width: 50px;
          height: 50px;
          text-align: center;
          border-radius: 50%;
          line-height: 50px;
          color: #fff;
          cursor: pointer;
          background: rgba(0, 0, 0, 0.5);
        }

        &:hover .avatar-hover {
          display: block;
        }
      }

      .username {
        display: block;
        line-height: 24px;
        font-size: 14px;
        margin-top: 6px;
      }
    }

    .custom-menu {
      width: 100%;
      margin-top: 20px;

      .menu-btn {
        width: 100%;
        padding: 12px 0 12px 40px;
        font-size: 15px;
        color: #333;
        cursor: pointer;
        transition: background 0.2s, color 0.2s;

        &.active {
          background: #f5f7fa;
          color: #409EFF;
        }
      }

      .sub-btn {
        width: 100%;
        padding: 10px 0 10px 60px;
        font-size: 14px;
        color: #666;
        background: #f9f9f9;
        cursor: pointer;
        transition: background 0.2s, color 0.2s;

        &.active {
          background: #e6f7ff;
          color: #409EFF;
        }
      }
    }
  }

  .main-content {
    flex: 1;
    padding: 24px;
    min-width: 0;
    min-height: 0;
    overflow: auto;
    background: rgb(255, 250, 240);
  }
}
</style>
